﻿using Ops.Host.Common.Extensions;
using Ops.Host.Core.Models;

namespace Ops.Host.Core.Services.Impl;

internal sealed class ArchiveInfoService : IArchiveInfoService
{
    private readonly IFreeSql _freeSql;

    public ArchiveInfoService(IFreeSql freeSql) => _freeSql = freeSql;

    public async Task<(List<Archive> items, long count)> GetPagedAsync(ArchiveInfoFilter filter, int pageIndex, int pageItems)
    {
        var items = await _freeSql.Select<Archive>()
                           .WhereIf(!string.IsNullOrEmpty(filter.Station), s => s.Station == filter.Station)
                           .WhereIf(!string.IsNullOrEmpty(filter.SN), s => s.SN == filter.SN)
                           .WhereIf(filter.CreatedTimeStart != null, s => s.CreatedAt >= filter.CreatedTimeStart.ToDayMin())
                           .WhereIf(filter.CreatedTimeEnd != null, s => s.CreatedAt <= filter.CreatedTimeEnd.ToDayMax())
                           .OrderBy(s => s.CreatedAt)
                           .Count(out var total)
                           .Page(pageIndex, pageItems)
                           .ToListAsync();
        return (items, total);
    }

    public List<ArchiveItem> GetArchiveItems(int archiveId)
    {
        var items = _freeSql.Select<ArchiveItem>().Where(s => s.ArchiveId == archiveId).ToList();
        return items;
    }
}
